package com.qinggeng.framework.config.mq.listener;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.qinggeng.framework.config.mq.core.GsdMessageService;
import com.qinggeng.framework.config.mq.handle.MessageHandle;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MessageListenerImpl implements MessageListener {
    private   final Map<Integer, MessageHandle> handleHashMap=new ConcurrentHashMap<>();

    private   final  String TYPE="type";

    private   final  String MESSAGE_ID="messageId";
    @Resource
    private GsdMessageService gsdMessageService;

    public  void registerHandleHashMap(Integer type,MessageHandle handle) {
        MessageHandle messageHandle=handleHashMap.get(TYPE);
        if (null == messageHandle) {
            handleHashMap.put(type, handle);
        }
    }

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String body=new String(message.getBody());
        log.info("message：{}", message.getMsgID());

        log.info("解析MQ-Body自定义内容：{}", body);
        JSONObject jsonObject= JSONObject.parseObject(body);
        try {
          Integer type=jsonObject.getInteger(TYPE);
            if (null ==type){
                return Action.ReconsumeLater;
            }
            MessageHandle messageHandle=handleHashMap.get(type);
            if (null ==messageHandle){
                return Action.ReconsumeLater;
            }
            messageHandle.handle(body);
            gsdMessageService.deleteGsdMessage(jsonObject.getString(MESSAGE_ID));
            return Action.CommitMessage;
        } catch (Exception e) {
            log.error("消费MQ消息失败，msgId:" + message.getMsgID() + "，ExceptionMsg：" + e.getMessage());
            return Action.ReconsumeLater;
        }
    }
}
